package com.ken.algorithms.hash;

import java.util.*;

/**
 * <ul>
 * <li>Title: LeetCode124Main</li>
 * <li>Description: TODO </li>
 * </ul>
 *
 * @author 程序员ken
 * @date 2021/10/16 15:09
 */
public class LeetCode124Main {

    //给定两个字符串 s 和 t ，编写一个函数来判断 t 是否是 s 的字母异位词。
    public static void main(String[] args) throws Exception {

        Scanner sc = new Scanner(System.in);

        System.out.println("请输入第一个字符串并回车");
        String s = sc.nextLine();

        System.out.println("请输入第二个字符串并回车");
        String t = sc.nextLine();

        //boolean result = isAnagram(s,t);
        boolean result = isAnagramByArray(s,t);

        System.out.println(result);
    }

    /**
     * 是否
     * @param s
     * @param t
     * @return
     * @throws Exception
     */
    private static boolean isAnagram(String s, String t) throws Exception {

        if(s==null||t==null){
            throw new Exception("string is null");
        }

        HashMap<Character,Integer> hashMap = new HashMap<Character,Integer>();

        char[] charS = s.toCharArray();

        Integer integer;
        for (int i = 0; i < charS.length; i++) {

            if(!hashMap.containsKey(charS[i])){
                hashMap.put(charS[i],1);//出现次数应该默认为1
            }else{
                hashMap.put(charS[i],hashMap.get(charS[i])+1);
            }
        }

        //一增一减
        char[] charsT = t.toCharArray();
        for (int i = 0; i < charsT.length; i++) {
            if(hashMap.containsKey(charsT[i])){
                hashMap.put(charsT[i],hashMap.get(charsT[i])-1);
            }
        }

        Set<Map.Entry<Character, Integer>> entries = hashMap.entrySet();
        Iterator<Map.Entry<Character, Integer>> iterator = entries.iterator();
        Map.Entry<Character, Integer> next;
        while (iterator.hasNext()){
            next = iterator.next();
            if(next.getValue()!=0){
                return false;
            }
        }

        return true;
    }


    /**
     * 字母 其他字符不行
     * @param s
     * @param t
     * @return
     * @throws Exception
     */
    private static boolean isAnagramByArray(String s, String t) throws Exception {

        if(s==null||t==null){
            throw new Exception("string is null");
        }

        int[] arr =new int[26];

        char[] charS = s.toCharArray();
        char[] charsT = t.toCharArray();

        for (char aChar : charS) {
            arr[aChar-'a']+= 1;
        }

        //一增一减
        for (char aChar : charsT) {
            arr[aChar-'a']-= 1;
        }

        for (int a : arr) {
            if(a!=0){
                return false;
            }
        }
        return true;
    }

}
